package com.four.reptile.config;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

public class GithubRepoPageProcessor implements PageProcessor {
    // 部分一：抓取网站的相关配置，包括编码、抓取间隔、重试次数等
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    @Override
    public void process(Page page) {
// 部分二：定义如何抽取页面信息，并保存下来
        page.putField("name", page.getHtml().xpath("/html/body/div[5]/div[3]/div/div[1]/div/div[3]/ul/li[1]/div/div[4]/a/em/text()").toString());
        page.putField("img",page.getHtml().css("div.p-img > a > img","data-lazy-img").toString());
        page.putField("price",page.getHtml().xpath("/html/body/div[5]/div[3]/div/div[1]/div/div[3]/ul/li[1]/div/div[3]/strong/i/text()").toString());
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new GithubRepoPageProcessor())
                //从"https://github.com/code4craft"开始抓 爬取网站
                .addUrl("https://search.jd.com/Search?keyword=%E5%8D%8E%E4%B8%BA&enc=utf-8&wq=%E5%8D%8E%E4%B8%BA&pvid=e8a41b67774d4aebb6b4e2d65190e8c8")
                .addPipeline(new JsonFilePipeline())
                //开启5个线程抓取
                .thread(5)
                //启动爬虫
                .run();
    }
}
